package com.ht.modules.system.config;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

/**
 * @author ht
 */
@Aspect
@Configuration
@Profile("prod")
@Slf4j
public class LogRecordAspect {
    @Pointcut("execution(public * com.ht.modules.*.*.*Controller.*(..))")
    public void execute() {
    }

    @Before("execute()")
    public void doBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info("------------------------------------------------------------------------------------------------------");
        log.info("Url : " + request.getRequestURL().toString());
        log.info("Http_Method : " + request.getMethod());
        log.info("Ip : " + request.getRemoteAddr());
        log.info("Class_Method : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("Args : " + Arrays.toString(joinPoint.getArgs()));
        log.info("------------------------------------------------------------------------------------------------------");
    }

    @After(value = "execute()")
    public void doAfter() {
        log.info("doAfter:");
    }

    @AfterReturning(returning = "result", pointcut = "execute()")
    public void doAfterReturning(Object result) {
        log.info("------------------------------------------------------------------------------------------------------");
        log.info("Response : " + result);
        log.info("------------------------------------------------------------------------------------------------------");
    }

    @AfterThrowing(pointcut = "execute()")
    public void doAfterThrowing() {
        log.error("doAfterThrowing: {}", " 异常情况!");
    }

}
